import 'dart:developer';
import 'dart:ui';

import 'package:charset_converter/charset_converter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shen_nai/app/user_controller.dart';
import 'package:shen_nai/config/app_colors.dart';
import 'package:shen_nai/routes/app_routes.dart';
import 'package:shen_nai/socket/socket_server_manage.dart';

//登录主页
class LoginView extends StatefulWidget {
  const LoginView({Key? key}) : super(key: key);

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  //手机号码输入控制器
  late TextEditingController _phoneController;
  //账号输入控制器
  late TextEditingController _accountController;
  //密码输入控制器
  late TextEditingController _passwordController;

  //登录方式 0.手机登录 1.账号登录
  int _type = 1;

  @override
  void initState() {
    super.initState();
    _phoneController = TextEditingController();
    _accountController = TextEditingController();
    _passwordController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    _phoneController.dispose();
    _accountController.dispose();
    _passwordController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 28),
      margin: const EdgeInsets.only(top: 58, left: 20, right: 20),
      decoration: const BoxDecoration(
          color: Color(0xFF2B2D32),
          borderRadius: BorderRadius.all(Radius.circular(32))),
      child: Column(
        children: [
          const Text(
            '欢迎登陆',
            style: TextStyle(
                color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(
            height: 30,
          ),
          Row(
            children: [
              const SizedBox(
                width: 14,
              ),
              Image.asset(
                'assets/images/account.png',
                width: 18,
              ),
              SizedBox(
                width: 20,
              ),
              Expanded(
                child: _type == 0
                    ? TextField(
                        controller: _phoneController,
                        maxLines: 1,
                        //textInputAction: TextInputAction.next,
                        keyboardType: TextInputType.phone,
                        cursorColor: Colors.white,
                        style:
                            const TextStyle(fontSize: 15, color: Colors.white),
                        decoration: const InputDecoration(
                            hintStyle:
                                TextStyle(color: Colors.white, fontSize: 15),
                            isDense: true,
                            hintText: '请输入手机号',
                            contentPadding: EdgeInsets.zero,
                            suffixIconConstraints: BoxConstraints(),
                            border: InputBorder.none),
                      )
                    : TextField(
                        controller: _accountController,
                        maxLines: 1,
                        //textInputAction: TextInputAction.next,
                        keyboardType: TextInputType.text,
                        cursorColor: Colors.white,
                        style:
                            const TextStyle(fontSize: 15, color: Colors.white),
                        decoration: const InputDecoration(
                            hintStyle:
                                TextStyle(color: Colors.white, fontSize: 15),
                            isDense: true,
                            hintText: '请输入账号',
                            contentPadding: EdgeInsets.zero,
                            suffixIconConstraints: BoxConstraints(),
                            border: InputBorder.none),
                      ),
              )
            ],
          ),
          Divider(
            color: Colors.white,
          ),
          _type == 0
              ? SizedBox(
                  height: 46,
                )
              : _getPasswordView(),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: [
          //     Row(
          //       children: [
          //         SizedBox(
          //           width: 14,
          //         ),
          //         InkWell(
          //           child: Text(
          //             '注册',
          //             style: TextStyle(color: Color(0xff2372FF)),
          //           ),
          //         )
          //       ],
          //     ),
          //     _type == 0
          //         ? SizedBox()
          //         : InkWell(
          //             child: Text(
          //               '忘记密码',
          //               style: TextStyle(color: Colors.white),
          //             ),
          //           )
          //     //InkWell()
          //   ],
          // ),
          Container(
            height: 44,
            width: double.infinity,
            margin: const EdgeInsets.only(top: 30, left: 22, right: 22),
            child: ElevatedButton(
              onPressed: () {
                _login();
              },
              style: ElevatedButton.styleFrom(
                  primary: AppColors.primary,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(22))),
              child: Text(
                '登 录',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            ),
          ),
          // SizedBox(
          //   height: 30,
          // ),
          // Image.asset(
          //   'assets/images/icon_or.png',
          //   height: 16,
          // ),
          // SizedBox(
          //   height: 20,
          // ),
          // OutlinedButton(
          //     onPressed: () {
          //       setState(() {
          //         if (_type == 0) {
          //           _type = 1;
          //         } else {
          //           _type = 0;
          //         }
          //       });
          //     },
          //     style: OutlinedButton.styleFrom(
          //       shape: RoundedRectangleBorder(
          //         borderRadius: BorderRadius.circular(8),
          //       ),
          //       side: const BorderSide(width: 1, color: Color(0xff3486F7)),
          //     ),
          //     child: Text(_type == 0 ? '账号密码登录' : '手机号登录',
          //         style: const TextStyle(
          //           color: Color(0xff3486F7),
          //         )))
        ],
      ),
    );
  }

  //登录
  _login() {
    if (_type == 0) {
      EasyLoading.showToast('手机登录暂无');
      return;
    } else {
      if (_accountController.text.isEmpty) {
        EasyLoading.showToast('账号不能为空');
        return;
      }
      if (_passwordController.text.isEmpty) {
        EasyLoading.showToast('密码不能为空');
        return;
      }
      EasyLoading.show(
          status: "加载中...",
          maskType: EasyLoadingMaskType.clear,
          dismissOnTap: true);
      SocketServerManage().writeData(
          'login ${_accountController.text} ${_passwordController.text}',
          (data) {
        EasyLoading.dismiss();
        CharsetConverter.decode('GBK', data).then((value) {
          log(value);
          if (value.contains('sucessed')) {
            EasyLoading.showToast('登录成功');
            var split = value.split(' ');
            log(split.toString());
            Get.find<UserController>()
              ..setPassword(_passwordController.text)
              ..setAccount(_accountController.text)
              ..setUsername(split[split.length - 2])
              ..setJurisdiction(int.parse(split[split.length - 1]));
            Get.offAllNamed(AppRoute.HOME);
          } else if (value.contains('alread')) {
            EasyLoading.showToast('登录成功');
            Get.offAllNamed(AppRoute.HOME);
          } else {
            EasyLoading.showToast('登录失败');
          }
        }, onError: (e) {
          log(e.toString());
        });
      });
    }
  }

  //密码控件
  Widget _getPasswordView() {
    return Column(
      children: [
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            SizedBox(
              width: 14,
            ),
            Image.asset(
              'assets/images/password.png',
              width: 18,
            ),
            SizedBox(
              width: 20,
            ),
            Expanded(
              child: TextField(
                controller: _passwordController,
                maxLines: 1,
                //textInputAction: TextInputAction.next,
                obscureText: true,
                keyboardType: TextInputType.visiblePassword,
                cursorColor: Colors.white,
                style: const TextStyle(fontSize: 15, color: Colors.white),
                decoration: const InputDecoration(
                    hintStyle: TextStyle(color: Colors.white, fontSize: 15),
                    isDense: true,
                    hintText: '请输入密码',
                    contentPadding: EdgeInsets.zero,
                    suffixIconConstraints: BoxConstraints(),
                    border: InputBorder.none),
              ),
            )
          ],
        ),
        Divider(
          color: Colors.white,
        ),
      ],
    );
  }
}
